<?php


namespace logicmodel;


use app\common\library\Email;
use comservice\GetRedis;
use comservice\Response;
use datamodel\Users;
use PHPMailer\PHPMailer\PHPMailer;



class EmailLogic
{


    /**
     * 发送邮件
     * @param $email
     * @param $type
     * @return array
     * @throws \PHPMailer\PHPMailer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendEmail($email,$type){
        $result = checkEmail($email);
        if(!$result) return Response::fail('邮箱格式错误');
        $info = (new Users())->where(['is_del' => 0, 'email' => $email])->find();
        if ($type == 1) {
            //注册
            if ($info) return Response::fail('邮箱已注册!');
        } elseif ($type == 2) {
            //忘记密码 修改密码 提币验证
            if (empty($info)) return Response::fail('邮箱未注册!');
        } elseif ($type == 3) {
            //订单通知
        } else {
            return Response::fail('短信类型错误');
        }
        $redis = GetRedis::getRedis();
        $emailCode = $redis->getItem($email);
        if($emailCode) return Response::fail('频繁发送');

        $code = rand(111111,999999);
        $name = config('site.name');
        $title = $name.'验证码';
        $body = "【{$name}】验证码：{$code}!";
        $emailModel =  new Email();
        $result = $emailModel->to($email)
            ->subject($title)
            ->message($body)
            ->send();
        if($result){
            $redis->setItem($email. '-' . $type,$code);
            $redis->settime($email. '-' . $type,45);
            return Response::success('发送成功');
        }
        return Response::fail('发送失败');
    }

}